package edu.xmut.yuepai.common.config;

import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import edu.xmut.yuepai.common.interceptor.TokenHandlerInterceptor;
import jakarta.annotation.Resource;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * @author shuofeng
 */
@ConditionalOnClass(DispatcherServlet.class)
@EnableWebMvc
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Resource
    FastJsonHttpMessageConverter customFastJsonHttpMessageConverter;

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(0, customFastJsonHttpMessageConverter);
    }


    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 允许跨域的路径
        registry.addMapping("/**")
                // 允许跨域请求的域名
                .allowedOriginPatterns("*")
                // 允许Cookie
                .allowCredentials(true)
                // 允许的请求方式
                .allowedMethods("*")
                // 允许的header属性
                .allowedHeaders("*")
                // 允许跨域的时间
                .maxAge(360000);

    }

    @Resource
    private TokenHandlerInterceptor tokenHandlerInterceptor;


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(tokenHandlerInterceptor)
                .addPathPatterns("/**")
                .order(-1);
    }
}